//
//  ViewController.m
//  QQMusic
//
//  Created by wwj on 16/4/21.
//  Copyright © 2016年 wwj. All rights reserved.
//

#import "ViewController.h"
#import "MusicTool.h"
#import "MusicTool.h"
#import "XMGMusic.h"
#import "AudioTool.h"
#import "CALayer+PauseAimate.h"
#import "MusicScrollView.h"
#import "LrcLable.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<UIScrollViewDelegate, AVAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *albumView;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *songLabel;
@property (weak, nonatomic) IBOutlet UILabel *singerLabel;
@property (weak, nonatomic) IBOutlet LrcLable *lrcLable;

@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *playOrPauseBtn;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet MusicScrollView *musicScrollview;

@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) CADisplayLink *lrcLink;

@property (strong, nonatomic) AVAudioPlayer *player;
@property (strong, nonatomic) XMGMusic *music;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
    
    [self paperMusic];
    
    self.musicScrollview.delegate = self;
}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    self.musicScrollview.contentSize = CGSizeMake(self.view.bounds.size.width * 2, 0);
}

- (void)setup{
    self.iconView.layer.cornerRadius = self.iconView.frame.size.width * 0.5;
    
    self.iconView.layer.borderColor = [UIColor colorWithRed:36 / 255.0 green:36 / 255.0 blue:36 / 255.0 alpha:1.0].CGColor;
    self.iconView.layer.borderWidth = 8.0;
    
    self.iconView.layer.masksToBounds = YES;
    
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateNormal];
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = @0;
    animation.toValue = @(M_PI * 2);
    animation.duration = 30.0;
    animation.repeatCount = NSIntegerMax;
    [self.iconView.layer addAnimation:animation forKey:nil];
    
    self.musicScrollview.lrcLable = self.lrcLable;
}

- (void)paperMusic{
    [self playWithMusic:[MusicTool currentMusic]];
}

- (IBAction)sliderBegin:(UISlider *)sender {
    [self removeProgressTimer];
}

- (IBAction)sliderValueChange:(UISlider *)slider {
    self.currentTimeLabel.text = [self stringWithTime:slider.value * self.player.duration];
}

- (IBAction)onTapProgressSlider:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:sender.view];
    CGFloat x = point.x / self.progressSlider.frame.size.width;
    self.player.currentTime = x * self.player.duration;
    [self addProgressTimer];
}

- (IBAction)sliderDidEnd:(UISlider *)sender {
    self.player.currentTime = sender.value * self.player.duration;
    [self addProgressTimer];
}

- (IBAction)onClickPlayerBtn {
    _playOrPauseBtn.selected = !_playOrPauseBtn.isSelected;
    if ([self.player isPlaying]) {
        [self.player pause];
        [self removeProgressTimer];
        [self removeLrcTimer];
        [self.iconView.layer pauseAnimate];
    }else{
        [self.player play];
        [self addProgressTimer];
        [self addLrcTimer];
        [self.iconView.layer resumeAnimate];
    }
}

- (IBAction)onClickPreBtn:(id)sender {
    [self playWithMusic:[MusicTool preMusic]];
}

- (IBAction)onClickNextBtn:(UIButton *)sender {
    [self playWithMusic:[MusicTool nextMusic]];
}



- (void)playWithMusic:(XMGMusic *)music{
    
    self.musicScrollview.musicName = music.lrcname;
    
    [AudioTool stopMusicWithName:[MusicTool currentMusic].filename];
    
    self.player =[AudioTool playMusicWithName:music.filename];
    self.player.delegate = self;
    [MusicTool setPlayMusic:music];
    _playOrPauseBtn.selected = self.player.isPlaying;
    self.music = music;
    
    _albumView.image = [UIImage imageNamed:music.icon];
    _iconView.image = [UIImage imageNamed:music.icon];
    _songLabel.text = music.name;
    _singerLabel.text = music.singer;
    _currentTimeLabel.text = [self stringWithTime:self.player.currentTime];
    _totalTimeLabel.text = [self stringWithTime:self.player.duration];
    
    [self removeProgressTimer];
    [self addProgressTimer];
    
    [self removeLrcTimer];
    [self addLrcTimer];
    
}

- (void)addLrcTimer{
    self.lrcLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLrc)];
    [self.lrcLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)removeLrcTimer{
    [self.lrcLink invalidate];
    self.lrcLink = nil;
}

- (void)addProgressTimer{
    [self updateProgressInfo];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgressInfo) userInfo:nil repeats:YES];
}

- (void)removeProgressTimer{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)updateLrc{
    self.musicScrollview.time = self.player.currentTime;
}

- (void)updateProgressInfo{
    self.currentTimeLabel.text = [self stringWithTime:self.player.currentTime];
    self.progressSlider.value = self.player.currentTime / self.player.duration;
}

- (NSString *)stringWithTime:(NSTimeInterval)time{
    NSInteger min = time / 60;
    NSInteger second = (NSInteger)time % 60;
    
    return [NSString stringWithFormat:@"%02ld:%02ld", min, second];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offetX = scrollView.contentOffset.x;
    CGFloat alpha = 1 - offetX / scrollView.bounds.size.width;
    self.lrcLable.alpha = alpha;
    self.singerLabel.alpha = alpha;
    self.iconView.alpha = alpha;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    if (flag) {
        [self onClickNextBtn:nil];
    }
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self onClickPlayerBtn];
            break;
            
        case UIEventSubtypeRemoteControlPreviousTrack:
            [self onClickPreBtn:nil];
            break;
            
        case UIEventSubtypeRemoteControlNextTrack:
            [self onClickNextBtn:nil];
            
        default:
            break;
    }
}

@end
